<route lang="yaml">
	meta:
	enabled: false
</route>

<script setup lang="ts">
	import { onMounted, ref } from 'vue'
	import { ElMessage, ElMessageBox } from 'element-plus'
	import { ElLoading } from 'element-plus'
	import GetCoupon from './getcoupon.vue'
	import userApi from '@/api/modules/users/user'
	import setupApi from '@/api/zhitan/setup.ts'
	import productApi from '@/api/zhitan/product.ts'

	import BigNumber from 'bignumber.js';

	// import dictApi from '@/api/modules/system/dict.ts'
	import sessionmanarge from '../sessionmanarge/index.vue'
	import Draggable from 'vuedraggable';
	// 编辑器
	import tinymce from 'tinymce/tinymce'
	import TinymceEditor from '@tinymce/tinymce-vue'
	import { useRoute } from 'vue-router'
	import type { FormInstance, UploadProps } from 'element-plus'
	// import Api from '@/api/modules/activity/activity'
	import useUserStore from '@/store/modules/user'
	import 'tinymce/themes/silver/theme'
	import 'tinymce/icons/default/icons'
	import 'tinymce/models/dom'
	import 'tinymce/plugins/autolink'
	import 'tinymce/plugins/autoresize'
	import 'tinymce/plugins/fullscreen'
	import 'tinymce/plugins/image'
	import 'tinymce/plugins/insertdatetime'
	import 'tinymce/plugins/link'
	import 'tinymce/plugins/lists'
	import 'tinymce/plugins/media'
	import 'tinymce/plugins/preview'
	import 'tinymce/plugins/table'
	import 'tinymce/plugins/wordcount'
	import 'tinymce/plugins/code'
	import 'tinymce/plugins/searchreplace'
	import useSettingsStore from '@/store/modules/settings'
	import { createDirectUploadTask, createMultipartUploadV2Task, FileData } from 'qiniu-js';


	const percent : any = ref(false)
	const percentnum : any = ref(0)
	const { setCustomTitle } = useMainPage()
	const baseurl : any = ref(`${import.meta.env.VITE_APP_API_BASEURLIMG}`)
	const formRef = ref<FormInstance>()
	const router = useRouter()
	const title : any = ref('新增产品')
	const loadicon = new URL('@/assets/images/loadicon.gif', import.meta.url).href
	const fullscreenLoading = ref(false)
	const settingsStore = useSettingsStore()
	const route = useRoute()
	const action : any = ref(`${import.meta.env.VITE_APP_API_BASEURL}upload/uploadImage`)
	const headers : any = ref({
		Authorization: `Bearer ${useUserStore().token}`,
	})

	const defaultSetting = ref({
		language_url: 'tinymce/langs/zh-Hans.js',
		language: 'zh-Hans',
		skin_url: settingsStore.settings.app.colorScheme === 'light' ? 'tinymce/skins/ui/oxide' : 'tinymce/skins/ui/oxide-dark',
		content_css: settingsStore.settings.app.colorScheme === 'light' ? 'tinymce/skins/content/default/content.min.css' : 'tinymce/skins/content/dark/content.min.css',
		min_height: 250,
		max_height: 320,
		min_width: 250,
		max_width: 375,
		content_style: 'video { width: 100%; margin: 0; padding: 0px; box-shadow: none; display: block; object-fit: contain; } img {max-width:100%;height:auto;vertical-align:top} ',
		selector: 'textarea',
		plugins: 'autolink autoresize fullscreen image insertdatetime link lists media preview table wordcount code searchreplace videoinfo',
		toolbar: 'undo redo | blocks | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | forecolor backcolor removeformat | link image media table insertdatetime searchreplace | preview code fullscreen',
		branding: false,
		menubar: false,
		toolbar_mode: 'sliding',
		insertdatetime_formats: [
			'%Y年%m月%d日',
			'%H点%M分%S秒',
			'%Y-%m-%d',
			'%H:%M:%S',
		],
		video_template_callback: function (data : any, video_class : any) {
			// 返回自定义的视频HTML
			return '<p style="width: 100%; object-fit: contain; height:auto; padding:0px; display:flex; justify-content:center; align-items:center;"><video class="' + video_class + '" style="width: 100%; object-fit: contain; margin:0; border:none;display: block;padding: 0px; box-shadow: none; " controls width="100%"  height="auto"  src="' + data.source + '"' +
				' poster="' + data.poster + '">' +
				'<source src="' + data.source + '"' +
				' type="' + data.source_mime + '"></source>' +
				'</video></p>';
		},
		file_picker_types: 'media',
		file_picker_callback: function (cb : any, value : any, meta : any) {
			if (meta.filetype == 'media') {
				//创建一个隐藏的type=file的文件选择input
				let input = document.createElement('input');
				input.setAttribute('type', 'file');
				input.onchange = function () {
					let file = this.files[0];//只选取第一个文件。如果要选取全部，后面注意做修改
					uploadvideo(file, (e : any) => {
						cb(e)
					})
				}
				//触发点击
				input.click();
			}
		},
		// https://www.tiny.cloud/docs/tinymce/6/file-image-upload/#images_upload_handler
		images_upload_handler: (blobInfo : any) => new Promise((resolve) => {
			// const img = `data:image/jpeg;base64,${blobInfo.base64()}`
			// resolve(img)
			upload(blobInfo, (e : any) => {
				resolve(e)
			})
		}),
	})
	setCustomTitle(route.query.parentId ? '编辑' : '新增')
	// const content = ref()

	const topIndex : any = ref(1)
	const topList : any = ref([
		{
			id: 1,
			name: '产品编辑',
			value: 1,
			num: 0,
		},
		{
			id: 2,
			name: '营期编辑',
			value: 2,
			num: 0,
		},
	])
	const tableData : any = ref([])
	const form : any = ref({
		status: 1,
		is_top: 1,
		labels: null,
		ability_labels: null,
		sort: 1,
		Integrate_switch: 0,
		coupon_switch: 0,
		group_switch: 0,
		allow_coupon_status:1
	})
	const openShowTishi : any = ref(false)
	const openShowlabel : any = ref(false)
	const labeltype : any = ref(1)
	const changevalue : any = ref(1)
	const switchidx : any = ref(1)
	const cakeList : any = ref([])
	const pactList : any = ref([])
	const labelsList : any = ref([])
	const labelvalue : any = ref("")



	const formRules = ref({
		name: [
			{ required: true, message: '请输入产品名称', trigger: 'blur' },
		],
		image: [
			{ required: true, message: '请上传封面图', trigger: 'blur' },
		],
		long_image: [
			{ required: true, message: '请上传产品长封面图', trigger: 'blur' },
		],
		images: [
			{ required: true, message: '请上传产品轮播图', trigger: 'blur' },
		],
		price: [
			{ required: true, message: '请输入销售价格', trigger: 'blur' },
		],
		scribing_price: [
			{ required: true, message: '请输入划线价格', trigger: 'blur' },
		],
		// labels: [
		// 	{ required: true, message: '请选择标签', trigger: 'blur' },
		// ],
		apply_notice: [
			{ required: true, message: '请添加购买须知', trigger: 'blur' },
		],
		safe_travel: [
			{ required: true, message: '请添加安全行程', trigger: 'blur' },
		],
		content: [
			{ required: true, message: '请添加产品详情', trigger: 'blur' },
		],
		goods_group_id: [
			{ required: true, message: '请选择产品分类', trigger: 'blur' },
		],
		Integrate: [
			{ required: true, message: '请输入赠送积分', trigger: 'blur' },
		],
		coupon_name: [
			{ required: true, message: '请选择关联优惠券', trigger: 'blur' },
		],
		group_num: [
			{ required: true, message: '请输入约伴人数', trigger: 'blur' },
		],
		group_coupon_name: [
			{ required: true, message: '请选择关联优惠券', trigger: 'blur' },
		],
		pact_id: [
			{ required: true, message: '请选择游学协议', trigger: 'blur' },
		],
		num: [
			{ required: true, message: '请输入成团人数', trigger: 'blur' },
		],


	})

	const coupontype : any = ref(null)
	const showGetCoupon : any = ref(false)

	onMounted(() => {
		getcakeList() // 分类
		getpactList() // 合同模板
		console.log('route:', route.query.parentId)
		if (route.query.type) {
			topIndex.value = Number(route.query.type)
		}
		if (route.query.parentId) {
			form.value.id = route.query.parentId.toString()
			getinfo()
			getScheduleList()
			title.value = '产品编辑'
		}
		if (!form.value.id) {
			topList.value[0].name = "产品添加"
			topList.value.splice(1, 1)
		}

		tinymce.init({})
	})
	function getLabelList() {
		// dictApi.index({ page: 1, limit: 100, dictId: 4 }).then((res : any) => {
		// 	if (res.code === 0) {
		// 		labelsList.value = res.data
		// 	}
		// })
	}
	function getScheduleList() {
		productApi.ProductSchedule_list({ page: 1, limit: 100, product_id: form.value.id }).then((res : any) => {
			if (res.code === 0) {
				tableData.value = res.data
			}

		})
	}

	function getcakeList() {
		productApi.ProductGroup_list({ page: 1, limit: 100, status: 1 }).then((res : any) => {
			if (res.code === 0) {
				res.data.forEach((item : any) => {
					item.id = item.id + ''
				})
				cakeList.value = res.data
			}
		})
	}
	const tabbar = useTabbar()
	// 返回列表页
	function goBack() {
		if (settingsStore.settings.tabbar.enable && settingsStore.settings.tabbar.mergeTabsBy !== 'activeMenu') {
			tabbar.close({ name: 'shopmanargeindex' })
		}
		else {
			router.push({ name: 'shopmanargeindex' })
		}
	}
	async function uploadvideo(blobInfo : any, fn : any) {
		console.log(blobInfo, 'blobInfoblobInfo')
		// fullscreenLoading.value = true
		// const formData = new FormData()
		// formData.append('file', blobInfo)
		// // 这里为自己的上传接口调用方法
		// userApi.upload(formData).then((res : any) => {
		// 	console.log(res, 'res')
		// 	fullscreenLoading.value = false
		// 	if (res) {
		// 		fn && fn(baseurl.value + res.url)
		// 	}
		// 	else {
		// 		ElMessage.error('图片上传失败')
		// 		fn && fn('')
		// 	}
		// })
		const token : any = await qiniu_token(blobInfo)
		const fileData : FileData = { type: 'file', data: blobInfo }
		let config = {
			useCdnDomain: true,
			region: 'z2', // 根据实际地区选择
			retryCount: 3, //上传自动重试次数  默认3次
			tokenProvider: () => {
				return Promise.resolve(token)
			},
		};
		const uploadTask = createMultipartUploadV2Task(fileData, config);
		console.log(uploadTask, 'uploadTask 1')

		percent.value = true
		// 设置进度回调函数
		uploadTask.onProgress((progress : any, context : any) => {
			// 处理进度回调
			// console.log(progress, context, progress.percent, 'context123')
			percentnum.value = Math.round((((progress.percent * 100) - 75) * 4 || 0))
			console.log(progress, context, progress.percent, percentnum.value, 'context123')
		});

		// 设置完成回调函数
		uploadTask.onComplete((result : any, context : any) => {
			// 处理完成回调
			console.log(JSON.parse(result), context, '设置完成回调函数')
			percentnum.value = 100
			let newResult = JSON.parse(result)
			// if (!form.value.name) {
			// 	form.value.name = file.name
			// }
			// form.value.file = newResult.key
			fn && fn(baseurl.value + '/' + newResult.key)
			console.log(newResult, 'newResultnewResult')
			// console.log(form.value, 'that.form')
			setTimeout(() => {
				percent.value = false
				ElMessage.success(`资源上传成功`)
				percentnum.value = 0
			}, 500)
		});

		// 设置错误回调函数
		uploadTask.onError((error : any, context : any) => {
			percent.value = 0
			console.log(error, context, '设置错误回调函数')
			percent.value = false
			ElMessageBox.alert('文件上传失败，请联系管理员', '提示', {
				callback: (action : any) => { },
			})

		});

		uploadTask.start()
	}

	// 获取7牛token
	function qiniu_token(file : any) {
		console.log(file)
		return new Promise((resolve : any, reject : any) => {
			userApi.getToken({
				ext: file.name.substring(file.name.lastIndexOf('.') + 1)
			}).then((res : any) => {
				console.log(res, 'resres')
				resolve(res.token)
			}).catch((err : any) => {
				ElMessageBox.alert('七牛token验证失败，请联系管理员', '提示', {
					callback: (action : any) => { },
				})
				reject(err)
			})
		});
	}
	async function upload(blobInfo : any, fn : any) {
		// const loadingInstance = ElLoading.service({
		// 	lock: true,
		// 	text: '上传中...',
		// 	background: 'rgba(0, 0, 0, 0.7)',
		// })
		// fullscreenLoading.value = true
		// const formData = new FormData()
		// formData.append('file', blobInfo.blob())
		// // 这里为自己的上传接口调用方法
		// userApi.upload(formData).then((res : any) => {
		// 	console.log(res, 'res')
		// 	fullscreenLoading.value = false
		// 	if (res) {
		// 		fn && fn(baseurl.value + res.url)

		// 	}
		// 	else {
		// 		ElMessage.error('图片上传失败')
		// 		fn && fn('')
		// 	}
		// })
		const token : any = await qiniu_token(blobInfo.blob())
		const fileData : FileData = { type: 'file', data: blobInfo.blob() }
		let config = {
			useCdnDomain: true,
			region: 'z2', // 根据实际地区选择
			retryCount: 3, //上传自动重试次数  默认3次
			tokenProvider: () => {
				return Promise.resolve(token)
			},
		};
		const uploadTask = createMultipartUploadV2Task(fileData, config);
		console.log(uploadTask, 'uploadTask 1')

		percent.value = true
		// 设置进度回调函数
		uploadTask.onProgress((progress : any, context : any) => {
			// 处理进度回调
			// console.log(progress, context, progress.percent, 'context123')
			percentnum.value = Math.round((((progress.percent * 100) - 75) * 4 || 0))
			console.log(progress, context, progress.percent, percentnum.value, 'context123')
		});

		// 设置完成回调函数
		uploadTask.onComplete((result : any, context : any) => {
			// 处理完成回调
			console.log(JSON.parse(result), context, '设置完成回调函数')
			percentnum.value = 100
			let newResult = JSON.parse(result)
			// if (!form.value.name) {
			// 	form.value.name = file.name
			// }
			// form.value.file = newResult.key
			fn && fn(baseurl.value + '/' + newResult.key)
			console.log(newResult, 'newResultnewResult')
			// console.log(form.value, 'that.form')
			setTimeout(() => {
				percent.value = false
				ElMessage.success(`资源上传成功`)
				percentnum.value = 0
			}, 500)
		});

		// 设置错误回调函数
		uploadTask.onError((error : any, context : any) => {
			percent.value = 0
			console.log(error, context, '设置错误回调函数')
			percent.value = false
			ElMessageBox.alert('文件上传失败，请联系管理员', '提示', {
				callback: (action : any) => { },
			})

		});

		uploadTask.start()

	}
	function closeLoad() {
		fullscreenLoading.value = false
	}
	function getinfo() {
		productApi.Product_info({ id: form.value.id }).then((res : any) => {
			if (res) {
				if (res.images) {
					res.images = res.images.split(',')
				}
				if (res.labels) {
					res.labels = res.labels.split(',')
				} else {
					res.labels = []
				}
				if (res.ability_labels) {
					res.ability_labels = res.ability_labels.split(',')
				} else {
					res.ability_labels = []
				}
				if (res.coupon_info) {
					res.coupon_name = res.coupon_info.name
					res.coupon_id = res.coupon_info.id
					res.coupon_type = res.coupon_info.type
					res.coupon_money = res.coupon_info.money
					if (res.coupon_info.type === 2) {
						res.coupon_type_about = res.coupon_info.product_group_info ? res.coupon_info.product_group_info.name : ''
					} else if (res.coupon_info.type === 3) {
						res.coupon_type_about = res.coupon_info.product_info ? res.coupon_info.product_info.name : ''
					}
				}
				if (res.group_coupon_info) {
					res.group_coupon_name = res.group_coupon_info.name
					res.group_coupon_id = res.group_coupon_info.id
					res.group_coupon_type = res.group_coupon_info.type
					res.group_coupon_money = res.group_coupon_info.money
					if (res.group_coupon_info.type === 2) {
						res.group_coupon_type_about = res.group_coupon_info.product_group_info ? res.group_coupon_info.product_group_info.name : ''
					} else if (res.group_coupon_info.type === 3) {
						res.group_coupon_type_about = res.group_coupon_info.product_info ? res.group_coupon_info.product_info.name : ''
					}
				}
				if (res.goods_group_id && typeof (res.goods_group_id) !== 'number') {
					res.goods_group_id = res.goods_group_id.split(',')
					// res.goods_group_id.forEach((i : any) => {
					// 	i = Number(i)
					// })
					// console.log(res.goods_group_id, 'res.goods_group_id')
				} else {
					res.goods_group_id = null
				}
				if (res.pact_id === 0) {
					res.pact_id = null
				}

				res.price = res.price / 100
				res.scribing_price = res.scribing_price / 100
				// form.value.Integrate


				form.value = res
				console.log(form.value, 'getinfo()')
			}
		})
	}
	function getpactList() {
		setupApi.Pact_list({ page: 1, limit: 100, status: 1 }).then((res : any) => {
			pactList.value = res.data
		})
	}
	function handleSuccess(res : any) {
		// const handleSuccess1: Uplofunction onCancel() {adProps['onSuccess'] = (res: any) => {
		console.log(res, 'res;;;')
		if (res) {
			// form.value.image = baseurl.value + res.data
			form.value.image = res
		}
		else {
			// ElMessage.warning(res.error)
			form.value.image = ""
		}
	}


	function handleSuccess01(res : any) {
		// const handleSuccess1: Uplofunction onCancel() {adProps['onSuccess'] = (res: any) => {
		console.log(res, 'res;;;')
		if (res) {
			form.value.images = form.value.images || []
			form.value.images.push(res)
			// form.value.image = res.data
		}
		else {
			// ElMessage.warning(res.error)
		}
	}

	function onCancel() {
		goBack()
	}

	function onSubmit() {

		formRef.value && formRef.value.validate((valid : any) => {
			if (valid) {
				ElMessageBox.confirm(
					'确认提交?',
					'提示',
					{
						confirmButtonText: '确认',
						cancelButtonText: '取消',
						type: 'warning',
					},
				)
					.then(() => {
						const isDecimal : any = ref(null)
						isDecimal.value = isDecimalfn(form.value.Integrate)
						if (form.value.Integrate_switch === 1 && (form.value.Integrate === 0 || !form.value.Integrate || isDecimal.value)) {
							ElMessage.warning('开启订单完成赠送积分按钮后，赠送积分数量需不小于1,且为整数')
							return
						}

						console.log(form.value, 'form.value')
						const images : any = ref("")
						const labels : any = ref("")
						const scribing_price : any = ref("")
						const ability_labels : any = ref("")
						const goods_group_id : any = ref("")
						const prices : any = ref("")

						if (form.value.labels) {
							labels.value = JSON.parse(JSON.stringify(form.value.labels)).join(',')
						}
						if (form.value.ability_labels) {
							ability_labels.value = JSON.parse(JSON.stringify(form.value.ability_labels)).join(',')
						} else {
							ability_labels.value = null
						}
						if (form.value.goods_group_id) {
							goods_group_id.value = JSON.parse(JSON.stringify(form.value.goods_group_id)).join(',')
						} else {
							goods_group_id.value = ""
						}

						if (form.value.images) {
							images.value = JSON.parse(JSON.stringify(form.value.images)).join(',')
						}
						// prices.value = Math.floor(JSON.parse(JSON.stringify(form.value.price)) * 100)
						// scribing_price.value = Math.floor(JSON.parse(JSON.stringify(form.value.scribing_price)) * 100)
						prices.value = new BigNumber(JSON.parse(JSON.stringify(form.value.price))).times(100).toNumber()
						scribing_price.value = new BigNumber(JSON.parse(JSON.stringify(form.value.scribing_price))).times(100).toNumber()

						const now = new Date();
						const fullTimestamp : any = Math.floor(now.getTime() / 1000)
						console.log(prices.value, scribing_price.value, 'form.value.scribing_price1')
						productApi.Product_edit({
							...form.value,
							images: images.value,
							labels: labels.value,
							price: prices.value,
							ability_labels: ability_labels.value,
							goods_group_id: goods_group_id.value,
							scribing_price: scribing_price.value,
							end_putaway_time: fullTimestamp,
						}).then((res : any) => {
							ElMessage({ message: '操作成功', type: 'success' })
							onCancel()
						})
					})
					.catch(() => {
						ElMessage({
							type: 'info',
							message: '已取消',
						})
					})
			}
		})
	}
	function isDecimalfn(num : any) {
		return num % 1 !== 0;
	}
	function changeSWitch(e : any) {
		switchidx.value = 1
		form.value.Integrate_switch = e === 1 ? 0 : 1
		console.log(form.value.Integrate_switch, 'openShowTishi.value')
		openShowTishi.value = true
		changevalue.value = e
	}
	function changeSWitch1(e : any) {
		switchidx.value = 2
		form.value.coupon_switch = e === 1 ? 0 : 1
		console.log(form.value.coupon_switch, 'openShowTishi.value')
		openShowTishi.value = true
		changevalue.value = e
	}
	function changeSWitch2(e : any) {
		switchidx.value = 3
		form.value.group_switch = e === 1 ? 0 : 1
		console.log(form.value.group_switch, e, 'openShowTishi.value')
		openShowTishi.value = true
		changevalue.value = e
	}
	function submitSwitch() {
		if (switchidx.value === 1) {
			form.value.Integrate_switch = changevalue.value
		} else if (switchidx.value === 2) {
			form.value.coupon_switch = changevalue.value
		} else if (switchidx.value === 3) {
			form.value.group_switch = changevalue.value
			console.log(form.value.group_switch, 'form.value.group_switch')
		}
		openShowTishi.value = false
	}
	function inputbrokerage(e : any) {
		console.log(e, form.value.price && form.value.price < form.value.scribing_price, '后即可立即')
		// if (form.value.price && form.value.price < form.value.scribing_price) {
		// 	ElMessage({
		// 		type: 'error',
		// 		message: '划线价不可大于正常价格',
		// 	})
		// 	e.target.value = null
		// 	form.value.scribing_price = null
		// }
		// form.distribution_price
	}
	function openshowGetCoupon(type : any) {
		coupontype.value = type
		showGetCoupon.value = true
	}
	function removecpupon(type : any) {
		if (type === 1) {
			form.value.coupon_name = null
			form.value.coupon_id = null
			form.value.coupon_type = null
			form.value.coupon_money = null
			form.value.coupon_type_about = null
		} else {
			form.value.group_coupon_name = null
			form.value.group_coupon_id = null
			form.value.group_coupon_type = null
			form.value.group_coupon_money = null
			form.value.group_coupon_type_about = null
		}
	}
	function changedata(e : any) {
		console.log(e, 'rrowrowrowowrrowrowrowow')
		if (coupontype.value === 1) {
			form.value.coupon_name = e.name
			form.value.coupon_id = e.id
			form.value.coupon_type = e.type
			form.value.coupon_money = e.money
			if (e.type === 2) {
				form.value.coupon_type_about = e.product_group_info ? e.product_group_info.name : ''
			} else if (e.type === 3) {
				form.value.coupon_type_about = e.product_info ? e.product_info.name : ''
			}


		} else {
			form.value.group_coupon_name = e.name
			form.value.group_coupon_id = e.id
			form.value.group_coupon_type = e.type
			form.value.group_coupon_money = e.money
			if (e.type === 2) {
				form.value.group_coupon_type_about = e.product_group_info ? e.product_group_info.name : ''
			} else if (e.type === 3) {
				form.value.group_coupon_type_about = e.product_info ? e.product_info.name : ''
			}
		}

		showGetCoupon.value = false
	}
	function addLabel(type : any) {
		labeltype.value = type
		openShowlabel.value = true
	}
	function submitLabel() {
		if (labeltype.value === 1) {
			form.value.labels = form.value.labels ? form.value.labels : []
			form.value.labels.push(labelvalue.value)
		} else {
			form.value.ability_labels = form.value.ability_labels ? form.value.ability_labels : []
			form.value.ability_labels.push(labelvalue.value)
		}
		openShowlabel.value = false
		labelvalue.value = ""
	}
	function removeLabel(j : any) {
		form.value.labels.splice(j, 1)
	}
	function blurPrice(e : any) {
		console.log(e.target.value, e.target, Number(e.target.value), '看就看')
		if (!form.value.id) {
			form.value.Integrate = Number(e.target.value)
		}
	}
</script>

<template>
	<div class="add">
		<!-- <page-header :title="title">
			<el-button size="default" round @click="goBack">
				<template #icon>
					<svg-icon name="ep:arrow-left" />
				</template>
				返回
			</el-button>
		</page-header> -->
		<PageHeader>
			<template #title>
				<div class="custom-style flex justify-between">
					<el-segmented v-model="topIndex" :options="topList" class="custom-style">
						<template #default="{ item }">
							<div class="flex flex-col items-center gap-2 p-2">
								<div>{{ item.name }}</div>
							</div>
						</template>
					</el-segmented>
					<el-button size="default" round @click="goBack">
						<template #icon>
							<svg-icon name="ep:arrow-left" />
						</template>
						返回
					</el-button>
				</div>
			</template>
		</PageHeader>
		<page-main style="height: calc(100vh - 290px);overflow-y: auto;" v-show="topIndex===1">
			<el-form ref="formRef" :model="form" :rules="formRules" label-width="96px">
				<div class="store-tit f18 fb mb-2">
					<span>基本信息</span>
				</div>

				<el-form-item label="产品封面：" prop="image" class="avatar">
					<ImageUpload v-model:url="form.image" :isneedwh="true" :width="3" :notip="true" :height="2"
						@onSuccess="handleSuccess" />
				</el-form-item>

				<el-form-item label="产品轮播：" prop="images" class="avatar">
					<ImagesUpload v-model:url="form.images" :notip="true" :width="3" :height="2" :max='9'
						@on-success="handleSuccess01($event)" />
				</el-form-item>
				<el-form-item label="产品名称：" prop="name">
					<el-input v-model="form.name" size="large" placeholder="请输入产品名称" clearable />
				</el-form-item>
				<el-row :gutter="24">
					<el-col :xs="8" :sm="24" :md="8" :lg="8">
						<el-form-item label="销售价格：" prop="price">
							<el-input-number v-model="form.price" style="width: 100%;" size="large" @blur="blurPrice"
								placeholder="请输入销售价格" :min="0" :max="999999999" controls-position="right"
								:precision="2" />
						</el-form-item>
					</el-col>
					<el-col :xs="8" :sm="24" :md="8" :lg="8">
						<el-form-item label="划线价：" prop="scribing_price">
							<el-input-number v-model="form.scribing_price" style="width: 100%;" size="large"
								@blur="inputbrokerage" placeholder="请输入划线价" :min="0" :max="999999999"
								controls-position="right" :precision="2" />
						</el-form-item>
					</el-col>
					<el-col :xs="8" :sm="24" :md="8" :lg="8">
						<el-form-item label="虚拟销量：">
							<el-input-number v-model="form.virtual_sales_volume" style="width: 100%;" size="large"
								placeholder="请输入虚拟销量" :min="0" :max="999999999" controls-position="right" />
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="24">
					<el-col :xs="24" :sm="24" :md="24" :lg="24">
						<el-form-item label="标签：" prop="labels">
							<!-- <el-select v-model="form.labels" multiple size="large" placeholder="请选择标签"
								style="width: 100%;">
								<el-option v-for="item in labelsList" :key="item.name" :label="item.name"
									:value="item.name" />
							</el-select> -->
							<div class=" flex flex-nowrap mr-2" style="max-width:90%; overflow-x: auto;">

								<draggable v-model="form.labels" item-key="id">
									<template #item="{element, index}">
										<el-tag class='py-1 mr-2 draggable-tag' size="large" closable
											@close="removeLabel(index)">
											{{ element }}
										</el-tag>
									</template>
								</draggable>

							</div>
							<el-button @click="addLabel(1)">
								新增
							</el-button>
						</el-form-item>
					</el-col>
					<!-- <el-col :xs="12" :sm="24" :md="12" :lg="12">
						<el-form-item label="能力标签：" prop="ability_labels"> 
							<div class='flex flex-wrap'> 
								<el-tag class='py-1 mr-2' v-for="(i,j) in form.ability_labels" :key="j" size="large"
									closable @close="removeLabel(2,j)">
									{{ i }}
								</el-tag>
								<el-button @click="addLabel(2)">
									新增
								</el-button>
							</div>
						</el-form-item>
					</el-col> -->
				</el-row>
				<el-form-item label="招募对象：" prop="age">
					<el-input v-model="form.age" size="large" placeholder="请输入招募对象" clearable />
				</el-form-item>
				<el-form-item label="领队配比：" prop="guide">
					<el-input v-model="form.guide" size="large" placeholder="请输入领队配比" clearable />
				</el-form-item>
				<el-form-item label="集合时间：" prop="gathering_time">
					<el-input v-model="form.gathering_time" size="large" placeholder="请输入集合时间" clearable />
				</el-form-item>
				<el-form-item label="集合地点：" prop="venue">
					<el-input v-model="form.venue" size="large" placeholder="请输入集合地点" clearable />
				</el-form-item>
				<el-form-item label="活动坐标：" prop="site">
					<el-input v-model="form.site" size="large" placeholder="请输入活动坐标" clearable />
				</el-form-item>


				<el-row :gutter="24">
					<el-col :xs="8" :sm="24" :md="8" :lg="8">
						<el-form-item label="成团人数：" prop="num">
							<!-- 	<el-input v-model="form.num" size="large" placeholder="请输入成团人数" clearable /> -->
							<el-input-number v-model="form.num" style="width: 100%;" size="large" placeholder="请输入成团人数"
								:min="1" controls-position="right" />
						</el-form-item>
					</el-col>
					<el-col :xs="8" :sm="24" :md="8" :lg="8">
						<el-form-item label="是否热门：" prop="is_top">
							<el-radio-group v-model="form.is_top">
								<el-radio :value="1">
									是
								</el-radio>
								<el-radio :value="0">
									否
								</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :xs="8" :sm="24" :md="8" :lg="8">
						<el-form-item label="排序：" prop="sort">
							<el-input-number v-model="form.sort" style="width: 100%;" size="large" placeholder="请输入排序号"
								:min="0" controls-position="right" />
						</el-form-item>
					</el-col>
					<el-col :xs="8" :sm="24" :md="8" :lg="8">
						<el-form-item label="产品分类：" prop="goods_group_id">
							<el-select multiple v-model="form.goods_group_id" size="large" placeholder="请选择产品分类"
								style="width: 100%;">
								<el-option v-for="item in cakeList" :key="item.id" :label="item.name"
									:value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<!-- <el-col :xs="6" :sm="24" :md="6" :lg="6">
						<el-form-item label="是否置顶：" prop="is_top">
							<el-radio-group v-model="form.is_top">
								<el-radio :value="1">
									是
								</el-radio>
								<el-radio :value="0">
									否
								</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col> -->
					<!-- <el-col :xs="6" :sm="24" :md="6" :lg="6">
						<el-form-item label="添加购买须知：" label-width="120" prop="purchase_notes_switch">
							<el-radio-group v-model="form.purchase_notes_switch">
								<el-radio :value="1">
									是
								</el-radio>
								<el-radio :value="0">
									否
								</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col> -->

					<el-col :xs="12" :sm="24" :md="12" :lg="12">
						<el-form-item label="产品状态：" prop="status">
							<el-radio-group v-model="form.status">
								<el-radio :value="1">
									在售
								</el-radio>
								<el-radio :value="2">
									待售
								</el-radio>
								<el-radio :value="3">
									预售
								</el-radio>
								<!-- <el-radio :value="4">
									禁用
								</el-radio> -->
							</el-radio-group>
						</el-form-item>
					</el-col>
				</el-row>
				<div class="store-tit f18 fb mb-2">
					<span>游学协议</span>
				</div>
				<el-form-item label="游学协议：" label-width="100px" prop="pact_id">
					<el-select v-model="form.pact_id" size="large" placeholder="请选择关联游学协议" style="width: 100%;">
						<el-option v-for="item in pactList" :key="item.id" :label="item.name" :value="item.id" />
					</el-select>
				</el-form-item>
				<div class="store-tit f18 fb mb-2">
					<span>营销板块</span>
				</div>
				<el-row :gutter="24">
					<el-col :xs="6" :sm="24" :md="6" :lg="6">
						<el-form-item label="订单核销赠送积分：" prop="Integrate_switch" label-width="160px">
							<!-- <el-switch @change="changeSWitch(form.Integrate_switch)" v-model="form.Integrate_switch"
								style="--el-switch-on-color: #13ce66; --el-switch-off-color: #dcdfe6" :active-value="1"
								:inactive-value="0" /> -->
							<el-switch v-model="form.Integrate_switch"
								style="--el-switch-on-color: #13ce66; --el-switch-off-color: #dcdfe6" :active-value="1"
								:inactive-value="0" />
						</el-form-item>
					</el-col>
					<el-col :xs="6" :sm="24" :md="6" :lg="6" v-if='form.Integrate_switch===1'>
						<el-form-item label="赠送积分：" label-width="120px" prop="Integrate">
							<el-input-number v-model="form.Integrate" style="width: 100%;" size="large"
								placeholder="请输入赠送积分" :min="0" :max="999999999" controls-position="right" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="24">
					<el-col :xs="6" :sm="24" :md="6" :lg="6">
						<el-form-item label="订单核销赠送优惠券：" prop="coupon_switch" label-width="160px">
							<!-- <el-switch @change="changeSWitch1(form.coupon_switch)" v-model="form.coupon_switch"
								style="--el-switch-on-color: #13ce66; --el-switch-off-color: #dcdfe6" :active-value="1"
								:inactive-value="0" /> -->
							<el-switch v-model="form.coupon_switch"
								style="--el-switch-on-color: #13ce66; --el-switch-off-color: #dcdfe6" :active-value="1"
								:inactive-value="0" />
						</el-form-item>
					</el-col>
					<el-col :xs="18" :sm="24" :md="18" :lg="18" v-if='form.coupon_switch===1'>
						<el-form-item label="关联优惠券：" label-width="120px" prop="coupon_name">
							<!-- <el-select v-model="form.coupon_id" size="large" placeholder="请选择关联优惠券"
								style="width: 100%;">
								<el-option v-for="item in cakeList" :key="item.id" :label="item.name"
									:value="item.id" />
							</el-select> -->
							<!-- <div @click="openshowGetCoupon(1)" style="width:100%;">
								<el-input style="width:100%;" v-model="form.coupon_name" size="large"
									placeholder="请添加关联优惠券" clearable />
							</div> -->
							<div v-if="form.coupon_name"
								class="flex mr-2  justify-center items-center px-2 py-1 relative"
								style="border:1px solid #999; border-radius: 4px; ">
								<div class="flex items-center py-1">
									<div class='c-[red] font-size-4'>￥{{form.coupon_money/100}}</div>
									<div class="font-size-3 ml-2">
										<div style="line-height:16px;">{{form.coupon_name}}</div>
										<div style="line-height:16px;"
											v-if="form.coupon_type===2 || form.coupon_type===3">
											<div v-if="form.coupon_type===2">
												仅限分类{{form.coupon_type_about}}使用</div>
											<div v-if="form.coupon_type===3">
												仅限产品{{form.coupon_type_about}}使用</div>
										</div>

									</div>
								</div>
								<div
									class="h-3 px-1 font-size-2.5  flex justify-center cursor-pointer items-center absolute top--0 left-0 bg-[red] c-[#fff]">
									{{form.coupon_type===1?'通用券':form.coupon_type===2?'品类券':form.coupon_type===3?'产品券':''}}
								</div>
								<div @click="removecpupon(1)"
									class="w-4 h-4 flex justify-center cursor-pointer items-center absolute top--0 right-0 bg-[#fff]">
									<svg-icon name="ep:close" />
								</div>
							</div>
							<div class="px-2 py-1 c-[#fff] flex justify-center cursor-pointer items-center bg-[#409eff]"
								style="border:1px solid #999; border-radius: 4px;" @click="openshowGetCoupon(1)">
								选择
							</div>
							<!-- <el-button type="primary" size="large" @click="openshowGetCoupon(1)">
								选择
							</el-button> -->
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="24">
					<el-col :xs="6" :sm="24" :md="6" :lg="6">
						<el-form-item label="约伴核销赠送优惠券：" prop="group_switch" label-width="160px">
							<!-- <el-switch @change="changeSWitch2(form.group_switch)" v-model="form.group_switch"
								style="--el-switch-on-color: #13ce66; --el-switch-off-color: #dcdfe6" :active-value="1"
								:inactive-value="0" /> -->
							<el-switch v-model="form.group_switch"
								style="--el-switch-on-color: #13ce66; --el-switch-off-color: #dcdfe6" :active-value="1"
								:inactive-value="0" />
						</el-form-item>
					</el-col>
					<el-col :xs="6" :sm="24" :md="6" :lg="6" v-if='form.group_switch===1'>
						<el-form-item label="约伴人数：" label-width="120px" prop="group_num">
							<el-input-number v-model="form.group_num" style="width: 100%;" size="large"
								placeholder="请输入约伴人数" :min="0" :max="999999999" controls-position="right" />
						</el-form-item>
					</el-col>
					<el-col :xs="12" :sm="24" :md="12" :lg="12" v-if='form.group_switch===1'>
						<el-form-item label="赠送优惠券：" label-width="120px" prop="group_coupon_name">
							<!-- <el-select v-model="form.group_coupon_id" size="large" placeholder="请选择约伴赠送优惠券"
								style="width: 100%;">
								<el-option v-for="item in cakeList" :key="item.id" :label="item.name"
									:value="item.id" />
							</el-select> -->
							<!-- <div @click="openshowGetCoupon(2)" style="width:100%;">
								<el-input style="width:100%;" v-model="form.group_coupon_name" size="large"
									placeholder="请添加关联优惠券" clearable />
							</div> -->
							<!-- <el-button type="primary" size="large" @click="openshowGetCoupon(2)">
								选择
							</el-button> -->
							<div v-if="form.group_coupon_name"
								class="flex mr-2  justify-center items-center px-2 py-1 relative"
								style="border:1px solid #999; border-radius: 4px; ">
								<div class="flex items-center py-1">
									<div class='c-[red] font-size-4'>￥{{form.group_coupon_money/100}}</div>
									<div class="font-size-3 ml-2">
										<div style="line-height:16px;">{{form.group_coupon_name}}</div>
										<div style="line-height:16px;"
											v-if="form.group_coupon_type===2 || form.group_coupon_type===3">
											<div v-if="form.group_coupon_type===2">
												仅限分类{{form.group_coupon_type_about}}使用</div>
											<div v-if="form.group_coupon_type===3">
												仅限产品{{form.group_coupon_type_about}}使用</div>
										</div>

									</div>
								</div>
								<div
									class="h-3 px-1 font-size-2.5  flex justify-center cursor-pointer items-center absolute top--0 left-0 bg-[red] c-[#fff]">
									{{form.group_coupon_type===1?'通用券':form.group_coupon_type===2?'品类券':form.group_coupon_type===3?'产品券':''}}
								</div>
								<div @click="removecpupon(2)"
									class="w-4 h-4 flex justify-center cursor-pointer items-center absolute top--0 right-0 bg-[#fff]">
									<svg-icon name="ep:close" />
								</div>
							</div>
							<div class="px-2 py-1 c-[#fff] flex justify-center cursor-pointer items-center bg-[#409eff]"
								style="border:1px solid #999; border-radius: 4px;" @click="openshowGetCoupon(2)">
								选择
							</div>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="24">
					<el-col :xs="6" :sm="24" :md="6" :lg="6">
						<el-form-item label="是否允许优惠券下单：" prop="group_switch" label-width="160px"> 
							<el-switch v-model="form.allow_coupon_status"
								style="--el-switch-on-color: #13ce66; --el-switch-off-color: #dcdfe6" :active-value="1"
								:inactive-value="2" />
						</el-form-item>
					</el-col> 
				</el-row>
				<div class="store-tit f18 fb mb-2">
					<span>图文板块</span>
				</div>
				<el-form-item label="图文详情：" prop="content">
					<div style="height: 680px; margin-bottom: 20px;">
						<TinymceEditor v-model="form.content" :init="defaultSetting" />
					</div>
				</el-form-item>
				<el-form-item label="安全行程：" prop="safe_travel">
					<div style="height: 680px; margin-bottom: 20px; ">
						<TinymceEditor v-model="form.safe_travel" :init="defaultSetting" />
					</div>
				</el-form-item>
				<el-form-item label="购买须知：" prop="apply_notice">
					<div style="height: 680px; margin-bottom: 20px; ">
						<TinymceEditor v-model="form.apply_notice" :init="defaultSetting" />
					</div>
				</el-form-item>
			</el-form>
		</page-main>
		<!-- <page-main style="height: calc(100vh - 290px);overflow-y: auto;" v-if="topIndex===2"> -->
		<div class="w-full " v-if="topIndex===2">
			<sessionmanarge :parseid="form.id"></sessionmanarge>
			<!-- <div class="flex w-full flex-wrap p-6" style="border:1px solid red;">
					<div v-for="(i,j) in tableData" :key="j" style="border:1px solid #ccc;"
						class="w-50 flex p-2 mr-4 mb-2 d-c c-[#e67c28] items-center justify-center">
						<div>{{i.name}}</div>
						<div class="mt-2">库存{{i.num-i.apply_num}}</div>
					</div>
				</div>
				<div class="mt-6 p-6" style="border:1px solid red;">
					<div v-for="(i,j) in tableData" :key="j" class="flex mb-2">
						<div class="font-size-6 mr-2 cursor-pointer">
							<div class="c-[#409eff]">
								<svg-icon name="ep:circle-plus" />
							</div>
							<div class="c-[red]">
								<svg-icon name="ep:remove" />
							</div>
						</div>
						<div class="w-80 p-2 mr-2 flex  items-center" style="border:1px solid #ccc;">营期：<el-input
								class="w-62" v-model="i.name" size="large" placeholder="请输入营期名称" clearable /></div>
						<div class="w-80 p-2 mr-2 flex  items-center" style="border:1px solid #ccc;">库存：<el-input
								class="w-62" style="border:none;" v-model="i.num" size="large" placeholder="请输入库存数量"
								clearable /></div>
						<div class="w-40 p-2 flex  items-center" style="border:1px solid #ccc;">排序：<el-input
								class="w-22" style="border:none;" v-model="i.sort" size="large" placeholder="请输入排序号"
								clearable /></div>
						<div class='w-18 ml-2'>
							<div class="px-2 py-4 c-[#fff] flex justify-center cursor-pointer items-center bg-[#409eff]"
								style="border:1px solid #999; border-radius: 4px;" @click="openshowGetCoupon(2)">
								添加
							</div>
						</div>
					</div>
				</div> -->
		</div>
		<!-- </page-main> -->
		<fixed-action-bar>
			<el-button type="primary" size="large" @click="onSubmit">
				提交
			</el-button>
			<el-button size="large" @click="onCancel">
				取消
			</el-button>
		</fixed-action-bar>

		<HDialog v-model="openShowTishi" :title="switchidx===1?'订单完成赠送积分':switchidx===2?'优惠券':switchidx===3?'约伴':``">
			<div style="padding: 0 18px;">
				<div class="flex py-16 d-c justify-center items-center">
					<SvgIcon class="rotate-180 c-[#409eff] font-size-24" name="i-ep:warning-filled" />
					<div class="mt-6">
						{{ `确认${changevalue===1?'开启':'关闭'}${switchidx===1?'订单完成赠送积分':switchidx===2?'优惠券':switchidx===3?'约伴':''}设置吗`}}
					</div>
					<!-- <div class="mt-2 font-size-3.5 c-[#606266]">
						{{`${changevalue===1?'开启':'关闭'}后将${changevalue===1?'不再按照分佣设置的分成模式分成，而会按照单产品佣金的设置模式':'不会再按照单产品佣金的设置模式，而会按照分佣设置的分成模式分成'}`}}
					</div> -->
				</div>
			</div>
			<template #footer>
				<div class="fotterbtn">
					<el-button class="cancel" @click="openShowTishi = false">
						取消
					</el-button>
					<el-button type="primary" @click="submitSwitch">
						{{`确认${changevalue===1?'开启':'关闭'}`}}
					</el-button>
				</div>
			</template>
		</HDialog>
		<HDialog v-model="openShowlabel" title="添加标签">
			<div style="padding: 0 18px;">
				<el-input v-model="labelvalue" size="large" placeholder="请输入标签" clearable />
			</div>
			<template #footer>
				<div class="fotterbtn">
					<el-button class="cancel" @click="openShowlabel = false">
						取消
					</el-button>
					<el-button type="primary" @click="submitLabel">
						保存
					</el-button>
				</div>
			</template>
		</HDialog>
		<GetCoupon v-if="showGetCoupon" v-model="showGetCoupon" @changedata="changedata($event)" />

		<!-- 上传时的加载遮罩层 -->
		<div v-if="fullscreenLoading" class="loading-mask">
			<div class="flex justify-center items-center d-c ">
				<div class=" c-[#409eff]">
					<img class="w-5 h-5" :src="loadicon" alt>
				</div>
				<div class="my-4 c-[#409eff]">上传中...</div>
				<!-- 添加关闭按钮 -->
				<!-- <el-button type="warning" @click="cancelUpload">取消上传</el-button> -->
				<div style="position: fixed; top:60px;right:60px; z-index:1000000;  border-radius: 50%; background-color: rgba(255, 255, 255, 0.8);"
					class="w-16 h-16 flex justify-center items-center font-size-10 cursor-pointer c-[#333]"
					@click="closeLoad">
					<svg-icon name="ep:close" />
				</div>
			</div>
		</div>
		<div v-if="percent" class="fixed demo-progress w-130 bg-[#fff]  top-50% left-50% "
			style="transform: translate(-50%,-50%); border-radius: 8px; box-shadow: 0px 0px 8px 0px #999; z-index:99999;">
			<!-- <div class="w-full text-end pr-4 pt-4 font-size-6 cursor-pointer" @click="closepercent">
				<svg-icon name="ep:close" />
			</div> -->
			<div class="w-full d-c flex justify-center items-center h-40  py-2 h-16" style=" ">
				<el-progress :width="500" striped striped-flow :text-inside="true" :stroke-width="24"
					:percentage="percentnum" status="success" />
				<div>
					<div class="my-4 c-[#67c23a]" v-if="percentnum>0">上传中...</div>
					<div class="my-4 c-[#e67c28]" v-else>正在解析文件流...</div>
				</div>
			</div>

		</div>
	</div>
</template>

<style scoped lang="scss">
	@import "@/assets/styles/tool";

	.loading-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.7);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 2000;
		/* 确保在el-loading之上 */
	}

	.el-loading {
		position: relative;
	}

	.demo-progress .el-progress--line {
		margin-bottom: 15px;
		width: 450px;
		height: 30px;
	}

	.el-loading .el-button {
		position: absolute;
		top: 10px;
		right: 10px;
	}

	.store-tit {
		position: relative;
		padding-left: 10px;
	}

	.store-tit::before {
		position: absolute;
		top: 50%;
		left: 0;
		width: 3px;
		height: 18px;
		content: "";
		background: var(--el-color-primary);
		border-radius: 4px;
		transform: translateY(-50%);
	}

	.avatar {
		:deep(.el-image) {
			width: 300px !important;
			height: 200px !important;
		}

		:deep(.image-slot) {
			width: 300px !important;
			height: 200px !important;
		}


		/* :deep(.el-upload__tip) {
    display: none !important;
  } */
	}

	.add {
		:deep(.tox-tinymce) {
			width: 375px !important;
			height: 675px !important;
		}
	}

	.draggable-tag {
		cursor: move;
		/* 鼠标悬停时显示为拖动图标 */
	}

	.draggable-tag:hover {
		cursor: grab;
		/* 鼠标悬停时显示为抓取图标 */
	}

	/* 当拖动开始时，改变光标样式 */
	.draggable-tag.sortable-chosen {
		cursor: grabbing;
	}
</style>